package pe.ejd.transformers;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractTransformer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class HelperTransformer extends AbstractTransformer{

	@Override
	protected Object doTransform(Object src, String enc)
			throws TransformerException {
		// TODO Auto-generated method stub
		DocumentBuilderFactory fctr = null;
		DocumentBuilder bldr = null;
		InputSource insrc = null;
		Document document = null;
		
		try {
					org.dom4j.tree.DefaultDocument xml = (org.dom4j.tree.DefaultDocument)src;
			String cadena = xml.asXML();
		
			System.out.println(cadena);

			File temp = File.createTempFile("temp-file-name", ".tmp");

			System.out.println("Temp file : " + temp.getAbsolutePath());

			BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
			bw.write(cadena);
			bw.close();

			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(temp);

			doc.getDocumentElement().normalize();

			NodeList nList = doc.getElementsByTagName("numeroCUJ");
			
			String numeroCUJ = "";
			
			for (int i = 0;i < nList.getLength(); i++) {
				 
				Node nNode = nList.item(i);
		 		if (nNode.getNodeType() == Node.ELEMENT_NODE) {
		 
					Element eElement = (Element) nNode;
					numeroCUJ = eElement.getFirstChild().getTextContent();
					System.out.println(numeroCUJ);		
				}
			}
			
			File salida = new File("C://Users//LIMA53//AnypointStudio//workspace//ejd-ws-consultas//xml//consultaExpedientePorNumero1.xml");

			BufferedReader reader = new BufferedReader( new FileReader(salida));
		    String         line = null;
		    StringBuilder  stringBuilder = new StringBuilder();
		    String         ls = System.getProperty("line.separator");

		    while( ( line = reader.readLine() ) != null ) {
		        stringBuilder.append( line );
		        //stringBuilder.append( ls );
		    }
			
		    System.out.println(stringBuilder);
			
		    cadena = stringBuilder.toString(); 
		    cadena =  cadena.replace("?", numeroCUJ);
		    
		    System.out.println(" final = " + cadena.trim());
		    
			fctr = DocumentBuilderFactory.newInstance();
			bldr = fctr.newDocumentBuilder();
			
			insrc = new InputSource(new StringReader(cadena.trim()));
			document = bldr.parse(insrc);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return document;

	}

}
